lunomods.getExperience = function(playername)
	local nowXP = lunomods.getCharValue(playername, "Experience") or 0
	if nowXP==nil or nowXP=="" or type(nowXP)~="number" or (type(nowXP)=="number" and nowXP<0) then 
		nowXP=0 
	else
		nowXP=math.floor(nowXP)
	end
	return nowXP
end

lunomods.getQuestStep = function(playername, questname)
	return lunomods.getCharValue(playername, questname) or 0
end

lunomods.getLevel = function(playername)
	local nowXP = lunomods.getExperience(playername)
	local lvl = math.floor(1 + math.sqrt(nowXP / 100))
	return lvl
end

lunomods.givePercentXP = function(player, percent, inLevel)
	if player~=nil and player:is_player() then
		local playername = player:get_player_name()
		local nowXP = lunomods.getExperience(playername)
		
		local lvl = 1
		if inLevel == nil then
			lvl = lunomods.getLevel(playername)
		else
			lvl = inLevel
		end
		local minXP = math.floor((100 * (lvl * lvl)) - (200 * lvl) + 100)
		local maxXP = math.floor((100 * ((lvl + 1) * (lvl + 1))) - (200 * (lvl + 1)) + 100)
		local addXP = (maxXP - minXP) * (percent / 100)
		local newXP = nowXP + addXP
		if newXP < 0 then newXP = 0 end
		lunomods.setCharValue(playername, "Experience", newXP)
		local lvlNEW = math.floor(1 + math.sqrt(newXP / 100))
		if lvl~=lvlNEW then
			if addXP > 0 then
				--minetest.sound_play("sfx_levelup", {object=player, max_hear_distance = 1000})  
				minetest.sound_play("sfx_levelup")
				minetest.chat_send_all(playername.." passou para o nivel "..lvlNEW.."!!!")
			elseif addXP < 0 then
				--minetest.sound_play("sfx_leveldown", {object=player, max_hear_distance = 1000})  
				minetest.sound_play("sfx_leveldown")
				minetest.chat_send_all(playername.." regrediu para o nivel "..lvlNEW.."!!!")
			end
			--TABELA DE NÍVEIS: https://docs.google.com/spreadsheet/ccc?key=0AqRrmO-Uhm1tdFVMLTVZQ0FSVUotTVI4Wi11dk1xclE&usp=sharing
		else
			if addXP > 0 then
				minetest.sound_play("sound_healing", {pos=player:getpos(), gain=6.0, max_hear_distance = 5,})
				minetest.chat_send_player(playername, "Voce ganhou '"..addXP.."' de experiencia!")  
			elseif addXP < 0 then
				minetest.sound_play("sound_poison", {pos=player:getpos(), gain=6.0, max_hear_distance = 5,})
				minetest.chat_send_player(playername, "Voce perdeu '"..addXP.."' de experiencia!")  
			end
		end
	end
end

lunomods.getExperienciaPorNivel = function(Nivel)
	return math.floor((100 * (Nivel * Nivel)) - (200 * Nivel) + 100)
end

lunomods.getNivelPorExperiencia = function(Experiencia)
	return math.floor(1 + math.sqrt(Experiencia / 100))
end
lunomods.getExperienciaPosMorte = function(nowXP) --Calcula novo XP do jogador quando morre!
	local lvl = lunomods.getNivelPorExperiencia(nowXP)
	local minXP = lunomods.getExperienciaPorNivel(lvl)
	local maxXP = lunomods.getExperienciaPorNivel(lvl + 1)
	local newXP = nowXP - ((maxXP - minXP) / 2)
	if newXP<0 then newXP=0 end
	return newXP
end
